package com.sanpu.kxe.business.repay.presenter;

import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;

import com.sanpu.kxe.R;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.provider.IMainProvider;
import com.sanpu.kxe.business.repay.bean.AreaOutput;
import com.sanpu.kxe.business.repay.bean.RepayCreditOutput;
import com.sanpu.kxe.business.repay.contract.RepayCreditContract;
import com.sanpu.kxe.business.repay.interfaces.IRepayCreditListener;
import com.sanpu.kxe.business.repay.model.RepayModel;
import com.sanpu.kxe.business.repay.provider.RepayOpenProvider;
import com.sanpu.kxe.business.trade.bean.PayCollectionOutput;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.interfaces.DialogViewListener;
import com.sanpu.kxe.module.dialog.GlobalDialog;
import com.sanpu.kxe.utils.DateUtils;
import com.sanpu.kxe.utils.DialogUtil;
import com.sanpu.kxe.utils.PublicProviderUtil;
import com.sanpu.kxe.utils.ToastUtil;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：代还首页
 * Created by 薛勇军 on 2019/4/10.
 */

public class RepayCreditPresenter implements RepayCreditContract.Presenter {

    private RepayCreditContract.View mView;

    private CompositeSubscription mSubscription;

    private RepayCreditOutput mCreditOutput;

    private String mAppCnlConfId;

    /** 是否自选行业 */
    private boolean isOptionalMcc = false;
    /** 是否停用 */
    private boolean isEnableStatus = false;

    public RepayCreditPresenter(RepayCreditContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void addCreditCard() {
        if (mCreditOutput != null) {
            RepayOpenProvider.getInstance().openAddCreditActivity(
                    mView.getContext(), mCreditOutput, CommonConfig.REQUESTCODE_REPAY_CREDIT);
        } else {
            ToastUtil.show("网络异常，请退出后重试！");
        }
    }

    @Override
    public void initViewData(PayCollectionOutput collectionOutput) {
        UserCenterOutput centerOutput = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        final String mAuthenState = centerOutput.getChkSts();
        try {
            if (!TextUtils.equals(CommonConfig.AUTHEN_PASS, mAuthenState)) {
                String remark = null;
                if (TextUtils.equals(CommonConfig.AUTHEN_NOTSUB, mAuthenState)) {
                    remark = "请先进行实名认证，再代还";
                } else if (TextUtils.equals(CommonConfig.AUTHEN_AUDIT, mAuthenState)) {
                    remark = "实名认证正在审核中，请稍候";
                } else if (TextUtils.equals(CommonConfig.AUTHEN_NOPASS, mAuthenState)) {
                    remark = "实名认证审核失败，请重新提交审核通过后才能代还";
                } else if (TextUtils.equals(CommonConfig.AUTHEN_NOCOMPLETION, mAuthenState)) {
                    remark = "需要补全资料才能代还";
                }

                if (!TextUtils.isEmpty(remark)) {
                    DialogUtil.getInstance().dialogNoTitletTwoBtnHaveCallBack(mView.getContext(),
                            remark, "取消", "确定",
                            new DialogViewListener() {
                                @Override
                                public void btnRightConfirm() {
                                    if (!TextUtils.equals(CommonConfig.AUTHEN_AUDIT, mAuthenState)) {
                                        openCertificationActivity();
                                    }
                                    ((Activity)mView.getContext()).finish();
                                }

                                @Override
                                public void btnLeftCancel() {
                                    ((Activity)mView.getContext()).finish();
                                }
                            });
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (collectionOutput != null) {
            isOptionalMcc = collectionOutput.isOptionalMcc();
            mAppCnlConfId = collectionOutput.getAppCnlConfId();
            index();
        }
    }

    @Override
    public void index() {
        mView.showLoadingDialog(false);
        Subscription subscription = RepayModel.getInstance().index(mAppCnlConfId)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RepayCreditOutput>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(RepayCreditOutput repayCreditOutput) {
                        mCreditOutput = repayCreditOutput;
                        mView.showDataView(repayCreditOutput);
                        if (repayCreditOutput != null) {
                            provinces(repayCreditOutput.getAdressVersion());
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 解绑信用卡
     */
    private void unbindCard(String cardId) {
        mView.showLoadingDialog(true);
        Subscription subscription = RepayModel.getInstance().unbindCard(cardId)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(String s) {
                        ToastUtil.show("信用卡解绑成功！");
                        index();
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 获取地址省市区
     */
    private void provinces(final String version) {
        AreaOutput areaOutput = CacheManage.getInstance().getCache(CacheModel.AREA_ENTITY);
        String adressVersion = CacheManage.getInstance().getCache(CacheModel.ADRESS_VERSION);
        if (areaOutput != null && version != null && TextUtils.equals(version, adressVersion)) {
            return;
        }
        Subscription subscription = RepayModel.getInstance().provinces()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AreaOutput>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("获取省市区", e.getMessage());
                    }

                    @Override
                    public void onNext(AreaOutput areaOutput) {
                        if (areaOutput != null) {
                            CacheManage.getInstance().saveCache(CacheModel.AREA_ENTITY, areaOutput);
                            CacheManage.getInstance().saveCache(CacheModel.ADRESS_VERSION, version);
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public IRepayCreditListener getRepayCreditListener() {
        return repayCreditListener;
    }

    /**
     * 监听事件
     */
    private IRepayCreditListener repayCreditListener = new IRepayCreditListener() {
        @Override
        public void onDeleteBank(RepayCreditOutput.RepayCredit repayCredit) {
            if (repayCredit != null) {
                String cardNo = repayCredit.getCardNo();
                final String cardId = repayCredit.getCardId();
                DialogUtil.getInstance().dialogNoTitletTwoBtnHaveCallBack(mView.getContext(),
                        "是否确定解绑尾号" + cardNo.substring(cardNo.length() - 4) + "的信用卡？", "取消", "确定",
                        new DialogViewListener() {
                            @Override
                            public void btnRightConfirm() {
                                unbindCard(cardId);
                            }

                            @Override
                            public void btnLeftCancel() {

                            }
                        });
            }
        }

        @Override
        public void onQueryClick(RepayCreditOutput.RepayCredit repayCredit) {

        }

        @Override
        public void onRefundClick(RepayCreditOutput.RepayCredit repayCredit) {
            if (isEnableStatus) {
                GlobalDialog dialog = new GlobalDialog(mView.getContext())
                        .title("温馨提示")
                        .content("该还款通道不可用，不能进行还款计划！");
                dialog.show();
                return;
            }
            if (mCreditOutput == null) return;
            if (!DateUtils.isSupportPaymentTime(mCreditOutput.getTradeTimeHorizon())) {
                String[] tranTm = mCreditOutput.getTradeTimeHorizon().split(",");
                String hint = "暂时不能还款，还款时间段：(" + tranTm[0] + "-" + tranTm[1] + ")。";
                new GlobalDialog(mView.getContext())
                        .content(hint)
                        .headerIcon(R.drawable.img_warm_prompt)
                        .show();
                return;
            }
            if (repayCredit != null) {
//                RepayOpenProvider.getInstance().openRefundActivity(mView.getContext(),
//                        mCreditOutput, repayCredit, isOptionalMcc);
            }
        }
    };

    @Override
    public void openRepaySupportActivity() {
        RepayOpenProvider.getInstance().openRepaySupportActivity(mView.getContext(), mAppCnlConfId);
    }

    /**
     * 实名认证
     */
    private void openCertificationActivity() {
        IMainProvider provider = PublicProviderUtil.getProvider(IMainProvider.class);
        if (provider != null) {
            provider.openCertificationActivity(mView.getContext(), true);
        }
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
